package com.coolcode.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coolcode.assember.CommonAssembler;
import com.coolcode.entity.UserInfo;
import com.coolcode.service.UserInfoService;
import com.coolcode.vo.PageVO;
import com.coolcode.vo.UserInfoVO;
import com.coolcode.vo.valid.Insert;
import com.coolcode.vo.valid.Update;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.groups.Default;

@Slf4j
@RestController
public class UserController {

    private UserInfoService userInfoService;

    private CommonAssembler assembler;

    @Autowired
    public UserController(UserInfoService userInfoService, CommonAssembler assembler) {
        this.userInfoService = userInfoService;
        this.assembler = assembler;
    }

    @PostMapping("/user/list")
    public ResponseEntity<Page<UserInfo>> getAllUser(@RequestBody @Validated(Default.class) PageVO<UserInfoVO> pageVO) {
        UserInfo userInfo = assembler.convertUserInfo(pageVO.getQuery());
        Wrapper wrapper = null;
        if (!StringUtils.isEmpty(userInfo.getUserName())) {
            wrapper = Wrappers.<UserInfo>lambdaQuery()
                    .like(UserInfo::getUserName, userInfo.getUserName());
        }

        Page<UserInfo> page = new Page<>();
        page.setCurrent(pageVO.getPageNum());
        page.setSize(pageVO.getPageSize());
        return new ResponseEntity<>(userInfoService.page(page, wrapper), HttpStatus.OK);
    }

    @PostMapping("/user")
    public ResponseEntity<Boolean> addUser(@RequestBody @Validated({Insert.class, Default.class}) UserInfoVO userInfoVO) {
        UserInfo userInfo = assembler.convertUserInfo(userInfoVO);
        return new ResponseEntity<>(userInfoService.save(userInfo), HttpStatus.OK);
    }

    @PutMapping("/user")
    public ResponseEntity<Boolean> updateUserById(@RequestBody @Validated({Update.class, Default.class}) UserInfoVO userInfoVO) {
        UserInfo userInfo = assembler.convertUserInfo(userInfoVO);
        return new ResponseEntity<>(userInfoService.updateById(userInfo), HttpStatus.OK);
    }

    @GetMapping("/user/{id}")
    public ResponseEntity<UserInfo> getUserById(@PathVariable("id") Integer id) {
        return new ResponseEntity<>(userInfoService.getById(id), HttpStatus.OK);
    }

    @DeleteMapping("/user/{id}")
    public ResponseEntity<Boolean> deleteUserById(@PathVariable("id") Integer id) {
        return new ResponseEntity<>(userInfoService.removeById(id), HttpStatus.OK);
    }
}
